<?php


/**
 *	备份数据库
 *	注意 ：将数据库分割成 一条条数据 好为上传做准备
 *		  将 ||| 写进字符串里面  
 */ 
function MySqlBackup(){
	$dbhost = C('DB_HOST'); //数据库主机名 
	$dbuser = C('DB_USER'); //数据库用户名 
	$dbpass = C('DB_PWD');  //数据库密码 
	$dbname = C('DB_NAME'); //数据库名
	$dbcharset = C('DB_CHARSET');// 数据库字符集
	mysql_connect($dbhost, $dbuser, $dbpass) or die("数据库连接失败，请核对后再试"); //连接数据库 
	mysql_select_db($dbname) or die ("不存在数据库: $dbname 请核对后再试");         //打开数据库 	
	mysql_query("set names 'utf8'");
	$mysql = "set charset utf8;|||\r\n";
	$q1 = mysql_query("show tables");
	while ($t = mysql_fetch_array($q1))
	{	
		$table = $t[0];
		$q2 = mysql_query("show create table `$table`");
		$sql = mysql_fetch_array($q2);
		$mysql .= $sql['Create Table'] . ";|||\r\n";
		$q3 = mysql_query("select * from `$table`");
		while ($data = mysql_fetch_assoc($q3))
		{
			$keys = array_keys($data);
			$keys = array_map('addslashes', $keys);
			$keys = join('`,`', $keys);
			$keys = "`" . $keys . "`";
			$vals = array_values($data);
			$vals = array_map('addslashes', $vals);
			$vals = join("','", $vals);
			$vals = "'" . $vals . "'";
			$mysql .= "insert into `$table`($keys) values($vals);|||\r\n";
		} 	
	} 
	mysql_close(); 
	$filename = C('DB_MYSQL').$dbname . date('YmdHis') . ".sql"; //存放路径，默认存放到项目最外层
	$fp = fopen($filename, 'w');
	fputs($fp, $mysql);
	fclose($fp);
	//echo "数据备份成功";
	return true;
}

/**
 * 	获取文件下面的文件列表
 */
function MyScandir($FilePath = './', $Order = 0) {
	$FilePath = opendir($FilePath);
	while (false !== ($filename = readdir($FilePath))) {
		$FileAndFolderAyy[] = $filename;
	}
	closedir($FilePath);
	$Order == 0 ? sort($FileAndFolderAyy) : rsort($FileAndFolderAyy);
	return $FileAndFolderAyy;
}

/**
 *	数据库上传
 */
function MySqlUpload(){
	$file_name = C('DB_MYSQL');     //读取要导入的SQL文件名 
	$dir = MyScandir($file_name, 1);//获取文件下面的文件列表
	$fileDir = $file_name.$dir[0];  //获取最近一次备份的文件
	$info = file_get_contents($fileDir);//读取最近一次备份的文件内容
	
	$dbhost = C('DB_HOST'); //数据库主机名 
	$dbuser = C('DB_USER'); //数据库用户名 
	$dbpass = C('DB_PWD');  //数据库密码 
	$dbname = C('DB_NAME'); //数据库名
	$dbcharset = C('DB_CHARSET');// 数据库字符集	
	set_time_limit(0);     //设置超时时间为0，表示一直执行。当php在safe mode模式下无效，此时可能会导致导入超时，此时需要分段导入 
	mysql_connect($dbhost, $dbuser, $dbpass) or die("数据库连接失败，请核对后再试");//连接数据库 
	mysql_select_db($dbname) or die ("不存在数据库: $dbname 请核对后再试");         //打开数据库 
	echo "<p>正在清空数据库,请稍等....<br>"; 
	$result = mysql_query("SHOW TABLES");
	while ($currow=mysql_fetch_array($result)) 
	{ 
		mysql_query("DROP TABLE IF EXISTS $currow[0]"); 
		echo "清空数据表【".$currow[0]."】成功！<br>"; 
	} 
	echo "<br>恭喜你清理MYSQL成功<br>"; 
	
	//读取文件内容，用|||分割成数组，上传到数据库
	$info = explode('|||',$info);
	foreach($info as $k => $v){
		mysql_query($v);
		unset($k);
	}
	mysql_close(); 
	echo "<br>导入完成！";	
} 

/**
 * 删除文件
 * $dir 目录
 */
function deldir($dir) { 
    //先删除目录下的文件： 
    $dh = opendir($dir); 
    while ($file = readdir($dh)) { 
        if ($file != "." && $file != "..") { 
            $fullpath = $dir . "/" . $file; 
            if (!is_dir($fullpath)) { 
                unlink($fullpath); 
            } else { 
                deldir($fullpath); 
            } 
        } 
    } 
 
    closedir($dh); 
    //删除当前文件夹： 
    if (rmdir($dir)) { 
        return true; 
    } else { 
        return false; 
    } 
}
//打印数组 
function p($array){
	echo '<pre>';
	print_r($array);
	echo '</pre>';
}

//16位密码加密算法
function mdPass($str){
	$info = md5(md5($str).'jiangchengzi');
	$info = substr($info,8,16); 
	return $info;
}

//数据对比
function check_pass($password,$pass){
	if($password !== $pass){
		return false;
	}else{
		return true;	
	}
} 

/**
 *	获取子分类的id
 *  $pid 主id
 */
function get_child_id($pid){
	$model = M('Category');
	$cate = $model->field('id,name,pid')->where(array('lock'=>1))->where('sort desc,id asc')->select();
	$array = getchilds($cate,$pid);
	$arr = array();
	foreach($array as $v){
		$arr[] = $v['id'];
	}
	$ids = implode(',',$arr);
	return $ids;
}


/*递归充足节点信息为多位数组
function node_merge($node,$pid=0){
	$arr = array();
	foreach($node as $v){
		if($v['pid'] == $pid){
			$v['child'] = node_merge($node,$v['id']);
			$arr[] = $v;
		}
	}
	return $arr; 
}*/
//递归重组 节点 权限 
function node_merge($node, $access = null, $pid=0){
	$arr = array();
	foreach($node as $v){
		if(is_array($access)){
			$v['access'] = in_array($v['id'],$access) ? 1 : 0;	
		}
		if($v['pid'] == $pid){
			$v['child'] = node_merge($node,$access,$v['id']);
			$arr[] = $v;
		}
	}
	return $arr; 
}


//组合成一维数组----无限极分类
function class_one_array($data, $pid = 0, $level = 0){
	$arr = array();
	foreach($data as $k => $v){
		if($v['pid'] == $pid){
			$v['level'] = $level + 1;
			$v['html'] = "└".str_repeat('─', $level * 2);
			$arr[]= $v;
			unset($data[$k]);
			$arr = array_merge($arr,class_one_array($data,$v['id'],$level+1));
		}
	}
	return $arr;
}

//组合多维数组----无限极分类
function class_much_array($data, $pid = 0 ,$level = 0) {
	$arr = array();
	foreach ($data as $k => $v) {
		if ($v['pid'] == $pid) {
			$v['level'] = $level + 1;
			$v['html'] = "└".str_repeat('─', $level * 2);
			$v['child'] = class_much_array($data, $v['id'],$level+1);
			$arr[] = $v;
			unset($data[$k]);
		}
	}
	return $arr;
}
	
//传递一个父级分类ID 返回所有子级分类
function getchilds ($cate, $pid) {
	$arr = array();
	foreach ($cate as $v) {
		if ($v['pid'] == $pid) {
			$arr[] = $v;
			$arr = array_merge($arr, getchilds($cate, $v['id']));
		}
	}
	return $arr;
}

//重组用户获得权限
function markNode($data, $pid = 1){
	$arr = array();
	foreach($data as $k => $v){
		if($v['pid'] == $pid){
			$v['node'] = markNode($data,$v['id']);
			$arr[] = $v;
			unset($data[$k]);
		}
	}	
	return $arr;
}

//获取用户权限的id
function checkAuthId(){
	//取出所有的权限节点
	$nodes = D('Node')->order('sort desc,id desc')->select();
	$node = markNode($nodes);
	//取出当前登录用户所有的模块权限（英文名称）和操作权限的
	$module = '';
	$node_id = '';
	$accessList = $_SESSION['_ACCESS_LIST'];
   
	return $accessList;
	exit;
	foreach($accessList as $key => $value){
		foreach($value as $key1 => $value1){
			$module .= ','.$key1;
			foreach($value1 as $key2 => $value2){
				$node_id .= ','.$value2; //
			}
		}
	}
	//p($module);
	//p($node_id);
	//去除没有权限的节点
	foreach($node as $key => $value){
		//p(strtoupper($value['name']));
		if(!in_array(strtoupper($value['name']),explode(',',$module))){
			unset($node[$key]);  //删除操作
		}else{
			//模块存在,比较里面的操作
			foreach($value['node'] as $key1 => $value1){
				if(!in_array($value1['id'],explode(',',$node_id))){
					unset($node[$key]['node'][$key1]);   //删除方法
				}
			}	
		}
	}
	$arr = array();
	foreach($node as $v){
		$arr[] = $v['id'];
		foreach($v['node'] as $vo){
			$arr[] = $vo['id'];
		}
	}
	//p($arr); //取出所有的权限的id
	return $arr;
}

//没有权限隐藏按钮
//没有权限隐藏按钮
function checkAuth($n){
	if(session(C('ADMIN_AUTH_KEY'))){
    	return true;
    }else{
        $nodeId = checkAuthId();
		$n = explode(',',$n);
		$result = array_intersect($n,$nodeId);  ////计算数组的交集
		if(!empty($result)){
			return true;
		}else{
			return false;
		}           
    }
}










